#include <APFFNDR.H>
#include <APGCLI.H>
#include <S32FILE.H>
#include <centralrepository.h>
#include <ProfileEngineSDKCRKeys.h>

#include <MrLockUi.rsg>
#include "MrLock.hrh"
#include "Utils.h"
#include "AppUi.h"

#include "ProfilesSettingPage.h"

CProfilesSettingPage::CProfilesSettingPage(CSelectionItemList* aList, TMyIntArray& aProfiles)
:CAknCheckBoxSettingPage(R_CHECKLIST_SETPAGE, aList), iProfiles(aProfiles), iSelectionList(aList)
{

}

CProfilesSettingPage::~CProfilesSettingPage()
{
	if (iSelectionList)
	{
		iSelectionList->ResetAndDestroy();
		delete iSelectionList;
		iSelectionList = NULL;
	}
}

CSelectionItemList* CProfilesSettingPage::CreateSelectionListL(const TMyIntArray& aProfiles)
{
	CSelectionItemList* list = new (ELeave) CSelectionItemList(8);
	CleanupStack::PushL(list);//+list
	CRepository* cr = CRepository::NewLC(KCRUidProfileEngine);//+cr

	for (TUint32 i = 0x00000002;i <0x32000002;i+= 0x01000000)
	{
		TUint32 profileId = i >> 24;
		TBuf<50> profileName;
		TInt err = cr->Get(i, profileName);
		if (err == KErrNone)
		{
			if (profileName.Length() == 0)
			{
				switch (i)
				{
					case 0x00000002:
						profileName.Copy(Utils::GetR(R_TEXT_GENERAL_PROFILE));
						break;
					case 0x01000002:
						profileName.Copy(Utils::GetR(R_TEXT_SILENT_PROFILE));
						break;
					case 0x02000002:
						profileName.Copy(Utils::GetR(R_TEXT_MEETING_PROFILE));
						break;
					case 0x03000002:
						profileName.Copy(Utils::GetR(R_TEXT_OUTDOOR_PROFILE));
						break;
					case 0x04000002:
						profileName.Copy(Utils::GetR(R_TEXT_PAGER_PROFILE));
						break;
					case 0x05000002:
						profileName.Copy(Utils::GetR(R_TEXT_OFFLINE_PROFILE));
						break;
				}		
			}
			if (profileName.Length())
			{
				TBool checked = aProfiles.Find(profileId) != KErrNotFound;
				CMySelectableItem* item = CMySelectableItem::NewL(profileName, checked, TUid::Uid(profileId));
				list->AppendL(item);

			}
		}
	}

	CleanupStack::PopAndDestroy();//-cr
	CleanupStack::Pop();//-list
	return list;
}

CProfilesSettingPage* CProfilesSettingPage::NewL(const TDesC& aTitle, TMyIntArray& aProfiles, TInt aInd)
{
	CSelectionItemList* list = CreateSelectionListL(aProfiles);
	CProfilesSettingPage * settingPage = new (ELeave) CProfilesSettingPage(list, aProfiles);

	CleanupStack::PushL(settingPage);//+page
	if (aInd != KErrNotFound)
		settingPage->SetSettingNumberL(aInd+1);
	settingPage->SetSettingTextL(aTitle);
	CleanupStack::Pop();//-page
	return settingPage;
}

void CProfilesSettingPage::AcceptSettingL()
{
	iProfiles.iCount = 0;
	CAknCheckBoxSettingPage::AcceptSettingL();

	for (TInt i = 0;i < iSelectionList->Count();i++)
	{
		CMySelectableItem* item = (CMySelectableItem*) iSelectionList->operator[](i);
		if (item->SelectionStatus())
		{
			iProfiles.Append(item->iUid.iUid);
		}
	}
}
